<template>
  <div class="questionnaire-reports">
    <!-- 统计概览 -->
    <el-row :gutter="24" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon color="#409EFF"><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.totalCount || 0 }}</div>
              <div class="stat-label">问卷总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon color="#67C23A"><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ averages.avgWakeTime?.toFixed(1) || 0 }}点</div>
              <div class="stat-label">平均起床时间</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon color="#E6A23C"><Moon /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ averages.avgSleepTime?.toFixed(1) || 0 }}点</div>
              <div class="stat-label">平均入睡时间</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon color="#F56C6C"><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ averages.avgCleanFreq?.toFixed(1) || 0 }}星</div>
              <div class="stat-label">平均打扫频率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表统计 -->
    <el-row :gutter="24" class="chart-row">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>作息时间分布</span>
          </template>
          <div ref="timeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>生活习惯分布</span>
          </template>
          <div ref="habitChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="24" class="chart-row">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>兴趣爱好统计</span>
          </template>
          <div ref="hobbiesChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>其他习惯统计</span>
          </template>
          <div ref="otherChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>详细问卷数据</span>
          <el-button type="primary" @click="exportData">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
      </template>

      <el-table :data="detailedList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="学号" width="100"/>
        <el-table-column prop="wakeTime" label="起床时间" width="100"/>
        <el-table-column prop="sleepTime" label="入睡时间" width="100"/>
        <el-table-column prop="holidayDiff" label="假期差异" width="100"/>
        <el-table-column prop="cleanFreq" label="打扫频率" width="100"/>
        <el-table-column prop="cleanTolerance" label="整洁容忍度" width="120"/>
        <el-table-column prop="studyNoise" label="介意噪音" width="100"/>
        <el-table-column prop="hobbies" label="兴趣爱好" min-width="150" show-overflow-tooltip/>
        <el-table-column prop="netTime" label="上网频率" width="100"/>
        <el-table-column prop="smoking" label="是否吸烟" width="100">
          <template #default="{ row }">
            <el-tag :type="row.smoking === '是' ? 'danger' : 'success'">
              {{ row.smoking }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="detailedList.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无问卷数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../../utils/request'
import * as echarts from 'echarts'

const statistics = ref({})
const averages = ref({})
const detailedList = ref([])
const loading = ref(false)

// 图表引用
const timeChartRef = ref()
const habitChartRef = ref()
const hobbiesChartRef = ref()
const otherChartRef = ref()

let timeChart = null
let habitChart = null
let hobbiesChart = null
let otherChart = null

const loadStatistics = async () => {
  loading.value = true
  try {
    const [statsResponse, detailResponse] = await Promise.all([
      request.get('/api/admin/questionnaire-report/statistics'),
      request.get('/api/admin/questionnaire-report/detailed-list')
    ])
    
    if (statsResponse.data.code === 200) {
      statistics.value = statsResponse.data.data
      averages.value = statsResponse.data.data.averages || {}
    }
    
    if (detailResponse.data.code === 200) {
      detailedList.value = detailResponse.data.data
    }
    
    // 等待DOM更新后初始化图表
    await nextTick()
    initCharts()
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

const initCharts = () => {
  initTimeChart()
  initHabitChart()
  initHobbiesChart()
  initOtherChart()
}

const initTimeChart = () => {
  if (!timeChartRef.value || !statistics.value.wakeTimeStats) return
  
  timeChart = echarts.init(timeChartRef.value)
  
  const wakeTimeData = Object.entries(statistics.value.wakeTimeStats || {}).map(([key, value]) => ({
    name: key,
    value
  }))
  
  const sleepTimeData = Object.entries(statistics.value.sleepTimeStats || {}).map(([key, value]) => ({
    name: key,
    value
  }))
  
  const option = {
    title: {
      text: '作息时间分布',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '10',
      left: 'center'
    },
    series: [
      {
        name: '起床时间',
        type: 'pie',
        radius: ['20%', '35%'],
        center: ['25%', '50%'],
        data: wakeTimeData,
        itemStyle: {
          color: function(params) {
            const colors = ['#74b9ff', '#0984e3', '#00b894', '#00a085', '#fdcb6e']
            return colors[params.dataIndex % colors.length]
          }
        }
      },
      {
        name: '入睡时间',
        type: 'pie',
        radius: ['20%', '35%'],
        center: ['75%', '50%'],
        data: sleepTimeData,
        itemStyle: {
          color: function(params) {
            const colors = ['#fd79a8', '#e84393', '#6c5ce7', '#a29bfe', '#fab1a0']
            return colors[params.dataIndex % colors.length]
          }
        }
      }
    ]
  }
  
  timeChart.setOption(option)
}

const initHabitChart = () => {
  if (!habitChartRef.value || !statistics.value.cleanFreqStats) return
  
  habitChart = echarts.init(habitChartRef.value)
  
  const cleanFreqData = Object.entries(statistics.value.cleanFreqStats || {})
  const cleanToleranceData = Object.entries(statistics.value.cleanToleranceStats || {})
  
  const option = {
    title: {
      text: '生活习惯分布',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['打扫频率', '整洁容忍度'],
      bottom: '10'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [...cleanFreqData.map(([key]) => key), ...cleanToleranceData.map(([key]) => key)]
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '打扫频率',
        type: 'bar',
        data: cleanFreqData.map(([, value]) => value),
        itemStyle: { color: '#74b9ff' }
      },
      {
        name: '整洁容忍度',
        type: 'bar',
        data: cleanToleranceData.map(([, value]) => value),
        itemStyle: { color: '#fd79a8' }
      }
    ]
  }
  
  habitChart.setOption(option)
}

const initHobbiesChart = () => {
  if (!hobbiesChartRef.value || !statistics.value.hobbiesStats) return
  
  hobbiesChart = echarts.init(hobbiesChartRef.value)
  
  const hobbiesData = Object.entries(statistics.value.hobbiesStats || {}).map(([key, value]) => ({
    name: key,
    value
  }))
  
  const option = {
    title: {
      text: '兴趣爱好统计',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '10',
      left: 'center'
    },
    series: [
      {
        name: '兴趣爱好',
        type: 'pie',
        radius: '60%',
        data: hobbiesData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  hobbiesChart.setOption(option)
}

const initOtherChart = () => {
  if (!otherChartRef.value || !statistics.value.netTimeStats) return
  
  otherChart = echarts.init(otherChartRef.value)
  
  const netTimeData = Object.entries(statistics.value.netTimeStats || {})
  const smokingData = Object.entries(statistics.value.smokingStats || {})
  const studyNoiseData = Object.entries(statistics.value.studyNoiseStats || {})
  
  const option = {
    title: {
      text: '其他习惯统计',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['上网频率', '吸烟情况', '噪音敏感'],
      bottom: '10'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['常玩', '一般', '不常玩', '是', '否', '介意', '有时', '不介意']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '上网频率',
        type: 'bar',
        data: [
          netTimeData.find(([key]) => key === '常玩')?.[1] || 0,
          netTimeData.find(([key]) => key === '一般')?.[1] || 0,
          netTimeData.find(([key]) => key === '不常玩')?.[1] || 0,
          0, 0, 0, 0, 0
        ],
        itemStyle: { color: '#74b9ff' }
      },
      {
        name: '吸烟情况',
        type: 'bar',
        data: [
          0, 0, 0,
          smokingData.find(([key]) => key === '是')?.[1] || 0,
          smokingData.find(([key]) => key === '否')?.[1] || 0,
          0, 0, 0
        ],
        itemStyle: { color: '#fd79a8' }
      },
      {
        name: '噪音敏感',
        type: 'bar',
        data: [
          0, 0, 0, 0, 0,
          studyNoiseData.find(([key]) => key === '是')?.[1] || 0,
          studyNoiseData.find(([key]) => key === '有时')?.[1] || 0,
          studyNoiseData.find(([key]) => key === '否')?.[1] || 0
        ],
        itemStyle: { color: '#00b894' }
      }
    ]
  }
  
  otherChart.setOption(option)
}

const exportData = () => {
  if (detailedList.value.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }
  
  // 创建CSV内容
  const headers = ['学号', '起床时间', '入睡时间', '假期差异', '打扫频率', '整洁容忍度', '介意噪音', '兴趣爱好', '上网频率', '是否吸烟']
  const csvContent = [
    headers.join(','),
    ...detailedList.value.map(item => [
      item.id,
      item.wakeTime,
      item.sleepTime,
      item.holidayDiff,
      item.cleanFreq,
      item.cleanTolerance,
      item.studyNoise,
      `"${item.hobbies || ''}"`,
      item.netTime,
      item.smoking
    ].join(','))
  ].join('\n')
  
  // 创建并下载文件
  const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `问卷统计报表_${new Date().toLocaleDateString()}.csv`
  link.click()
  
  ElMessage.success('数据导出成功')
}

const handleResize = () => {
  if (timeChart) timeChart.resize()
  if (habitChart) habitChart.resize()
  if (hobbiesChart) hobbiesChart.resize()
  if (otherChart) otherChart.resize()
}

onMounted(() => {
  loadStatistics()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (timeChart) timeChart.dispose()
  if (habitChart) habitChart.dispose()
  if (hobbiesChart) hobbiesChart.dispose()
  if (otherChart) otherChart.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.questionnaire-reports {
  padding: 0;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stat-icon {
  margin-right: 15px;
  font-size: 32px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.chart-row {
  margin-bottom: 24px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}
</style>
